package com.xinsmartsky.penmaji.penmaji;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class SynchronizedDemoActivity implements Runnable {
    int b = 1;

    public synchronized void s1() throws Exception {
        b = 1;
        Thread.sleep(5000);
        System.out.println("b = " + b);
    }

    //若s2无synchronized,s1睡眠时 值被改变  b = 2
    //若两个地方都改了对象  则两个地方都要加同步
    public synchronized void s2() throws Exception {
        Thread.sleep(2000);
        b = 2;
    }

    @Override
    public void run() {
        try {
            s1();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        SynchronizedDemoActivity ss = new SynchronizedDemoActivity();
        Thread t = new Thread(ss);
        t.start();
        ss.s2();
        //过程：主线程执行s2---锁住---同时其它有锁syn,,的线程不能执行---s2执行后执行s1
        //synchronized的作用：1、同时刻只有一个线程可以访问此段程序；2、获得synchronized才能执行（其它有synchronized的不能执行）
        System.out.println(ss.b);//对象失望全局变量

    }
/*运行
1
b = 1*/
}
